package com.java2104.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java2104.entity.Website;
import com.java2104.mapper.WebsiteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.List;

@Service
public class WebsiteService {
    @Autowired
    private WebsiteMapper websiteMapper;

    /**
     * 分页查找站点
     * @param name 站点名称
     * @param country 所属国家
     * @param pageNum 页号（第几页）
     * @param pageSize 每页显示几条
     * @return 封装了查询结果的分页对象
     */
    public PageInfo<Website> search(String name, String country, int pageNum, int pageSize) {
        //开始分页
        PageHelper.startPage(pageNum, pageSize);
        //查询列表
        List<Website> list = websiteMapper.selectList(name, country);
        //封装查询结果及分页信息
        PageInfo<Website> pageInfo = new PageInfo<>(list);
        return pageInfo;//调用Mapper返回站点列表
    }

    public List<String> searchCountry() {
        return websiteMapper.selectCountryList();
    }

    public boolean save(Website website) {
        return websiteMapper.insert(website) > 0;
    }

    public boolean remove(int id) {
        return websiteMapper.deleteByPrimaryKey(id) > 0;
    }

    public void access(int siteId) {
        Date today = new Date(System.currentTimeMillis());//获取系统当天的日期
        if (websiteMapper.selectCount(siteId, today)==0) {//当天第一次访问
            websiteMapper.insertAccessLog(siteId, today);
        } else {//不是第一次访问
            websiteMapper.updateAccessCount(siteId, today);
        }
    }
}
